package com.example.rbacmanage.interceptor;

import com.alibaba.druid.support.json.JSONUtils;
import com.example.rbacmanage.entity.system.User;
import com.example.rbacmanage.mapper.system.UserMapper;
import com.example.rbacmanage.util.JwtTokenUtil;
import com.example.rbacmanage.util.SpringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DefinedInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        System.out.println("web拦截器");
        String token = request.getHeader("Authorization");
        System.out.println("token:"+token);
        String username = JwtTokenUtil.getUsernameFromToken(token);
        //用户是否存在
       UserMapper userMapper = SpringUtils.getBean("userMapper");
        User user = userMapper.queryOneByUsername(username);
        if (user == null){
            try {
                Map<String,Object> map = new HashMap<>();
                map.put("code",500);
                map.put("msg","用户不存在");
                response.getWriter().write(JSONUtils.toJSONString(map));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return false;
        }
        return true;
    }
}
